package org.qb.mapreduce.mapJoinDemo;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class MapJoinMapper extends Mapper <LongWritable, Text,Text, NullWritable>{

    private Map<String,String> pdMap = new HashMap<>();
    private Text text = new Text();

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {

        //通过缓存文件得到小表数据pd.txt
        URI[] cacheFiles = context.getCacheFiles();
        Path path = new Path(cacheFiles[0]);

        //抓取文件对象，并开流
        FSDataInputStream fsDataInputStream = FileSystem.get(context.getConfiguration()).open(path);

        //通过包装流转换为Reader，方便读取
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(fsDataInputStream, StandardCharsets.UTF_8));

        //逐行读取
        String line;

        while (StringUtils.isNotEmpty(line = bufferedReader.readLine())){
            //切割一行
            String[] split = line.split("\t");
            pdMap.put(split[0],split[1] );
        }

        IOUtils.closeStream(fsDataInputStream);
    }

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {

        //获取大表数据
        String[] split = value.toString().split("\t");

        String productName = pdMap.get(split[1]);

        text.set(split[0] + "\t" + productName + "\t" + split[2]);

        context.write(text,NullWritable.get());
    }
}
